import MyTable from "@/components/MyTable";
import { Button, Popconfirm, message } from "antd";
import { useMemo, useRef } from "react";

import ButtonGroup from "@/components/ButtonGroup";
import { delType, getTypePage } from "@/services/type";
import { useBoolean, useRequest } from "ahooks";
import Add from "./Add";

export default () => {
  const [open, { toggle: toggleOpen }] = useBoolean(false);
  const { run: del } = useRequest(delType, {
    manual: true,
    onSuccess: () => {
      message.success("删除成功");
      refresh();
    },
  });
  const { data: typeList, run: refresh } = useRequest(getTypePage);

  const columns = useMemo(() => {
    return [
      {
        title: "序号",
        dataIndex: "index",
        render: (v, item, index) => (
          <>{index + 1 }</>
        ),
      },
      {
        title: "名称",
        dataIndex: "name",
      },
      {
        title: "描述",
        dataIndex: "description",
      },
      {
        title: "操作",
        dataIndex: "action",
        align: "center",
        render: (_, record) => {
          const {id } = record;
          return (
            <ButtonGroup>
              <Popconfirm
                placement="topLeft"
                title={"确认删除吗？"}
                okText="确认"
                cancelText="取消"
                onConfirm={() => del([id])}
              >
                <Button type="link">删除</Button>
              </Popconfirm>
            </ButtonGroup>
          );
        },
      },
    ];
  }, []);

  return (
    <>
      <MyTable
        top={
          <div>
            <Button onClick={() => toggleOpen()} type="primary">
              新增分类
            </Button>
          </div>
        }
        hasIndex={false}
        rowKey={"id"}
        columns={columns}
        dataSource={typeList}
      />
      {open && (
        <Add
          open={open}
          close={toggleOpen}
          refresh={refresh}
        />
      )}
    </>
  );
};
